package com.guli.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.common.constant.MqConstant;
import com.guli.common.to.mq.StockDetailTo;
import com.guli.common.to.mq.StockLockedTo;
import com.guli.common.utils.R;
import com.guli.ware.dao.WareSkuDao;
import com.guli.ware.entity.WareOrderTaskDetailEntity;
import com.guli.ware.entity.WareOrderTaskEntity;
import com.guli.ware.feign.OrderFeignService;
import com.guli.ware.service.WareOrderTaskDetailService;
import com.guli.ware.service.WareOrderTaskService;
import com.guli.ware.service.WareSkuService;
import com.guli.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author zzb
 * @Date 2024/5/31 17:17
 * @Version 1.0
 * @description
 */
@RabbitListener(queues = {MqConstant.STOCK_RELEASE_QUEUE/*,MqConstant.PMS_CANAL_QUEUE*/})
@Component
@Slf4j
public class StockReleaseListener {
    @Autowired
    private OrderFeignService orderFeignService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private WareSkuDao wareSkuDao;

    /**
     * 订单关闭，解锁库存
     * @param orderVo
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleCloseOrderRelease(OrderVo orderVo, Message message, Channel channel) {
        try {
            log.info("{} => {} => 订单关闭，解锁库存中", LocalDateTime.now(), orderVo.getOrderSn());
            String orderSn = orderVo.getOrderSn();
            //根据订单号查询库存工作单
            WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
            //获取库存工作单号
            Long id = wareOrderTaskEntity.getId();
            List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService
                    .list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("order_task_id", id)
                            .eq("lock_status", 1));
            for (WareOrderTaskDetailEntity entity : entities) {
                unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException ex) {
                log.info(ex.getMessage());
            }
        }
    }

    /**
     * 锁定库存后解锁库存
     * @param stockLockedTo
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void HandleStockRelease(StockLockedTo stockLockedTo, Message message, Channel channel) {
        StockDetailTo detailTo = stockLockedTo.getStockDetailTo();
        Long detailToId = detailTo.getId();
        //根据详情id查询订单详细
        WareOrderTaskDetailEntity taskDetailEntity = wareOrderTaskDetailService.getById(detailToId);
        if (taskDetailEntity != null) {
            //获取库存工作单详细ID
            Long id = taskDetailEntity.getId();
            //根据库存工作单详细ID查询该工作单详细
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
            //获取订单号
            String orderSn = orderTaskEntity.getOrderSn();
            R result = orderFeignService.getOrderStatusByOrderSn(orderSn);
            if (result.getCode() == 0) {
                OrderVo orderVo = result.getData(new TypeReference<OrderVo>() {
                });
                if (orderVo == null || orderVo.getStatus() == 4) {
                    //当前状态为1，已锁定且未解锁才可以解锁
                    if (taskDetailEntity.getLockStatus() == 1) {
                        unLockStock(taskDetailEntity.getSkuId(), taskDetailEntity.getWareId(),
                                taskDetailEntity.getSkuNum(), taskDetailEntity.getId());
                    }
                    try {
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                //消息拒绝以后重新放到队列里面，让别人继续消费解锁
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            //无需解锁
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void unLockStock(Long skuId, Long wareId, Integer skuNum, Long detailId) {
        wareSkuDao.unLockStock(skuId, wareId, skuNum);
        WareOrderTaskDetailEntity wareOrderTaskDetail = new WareOrderTaskDetailEntity();
        wareOrderTaskDetail.setId(detailId);
        wareOrderTaskDetail.setLockStatus(2);
        wareOrderTaskDetailService.updateById(wareOrderTaskDetail);
    }

}
